/**
 * 日志级别枚举
 */
export enum LogLevel {
  DEBUG = 'DEBUG',
  INFO = 'INFO',
  WARN = 'WARN',
  ERROR = 'ERROR',
}

/**
 * 日志记录器类
 */
class LoggerService {
  private readonly name: string;
  private readonly colors = {
    DEBUG: '\x1b[36m', // 青色
    INFO: '\x1b[32m', // 绿色
    WARN: '\x1b[33m', // 黄色
    ERROR: '\x1b[31m', // 红色
    RESET: '\x1b[0m', // 重置
  };

  constructor(name: string) {
    this.name = name;
  }

  /**
   * 格式化时间戳
   */
  private formatTimestamp(): string {
    return new Date().toISOString();
  }

  /**
   * 格式化日志消息
   */
  private formatMessage(
    level: LogLevel,
    message: string,
    ...args: any[]
  ): string {
    const timestamp = this.formatTimestamp();
    const color = this.colors[level];
    const reset = this.colors.RESET;

    let formattedMessage = `${color}[${timestamp}] [${level}] [${this.name}]${reset} ${message}`;

    if (args.length > 0) {
      formattedMessage +=
        ' ' +
        args
          .map(arg =>
            typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
          )
          .join(' ');
    }

    return formattedMessage;
  }

  log(message: string, ...args: any[]): void {
    console.log(this.formatMessage(LogLevel.INFO, message, ...args));
  }

  /**
   * 调试日志
   */
  debug(message: string, ...args: any[]): void {
    console.debug(this.formatMessage(LogLevel.DEBUG, message, ...args));
  }

  /**
   * 信息日志
   */
  info(message: string, ...args: any[]): void {
    console.info(this.formatMessage(LogLevel.INFO, message, ...args));
  }

  /**
   * 警告日志
   */
  warn(message: string, ...args: any[]): void {
    console.warn(this.formatMessage(LogLevel.WARN, message, ...args));
  }

  /**
   * 错误日志
   */
  error(message: string, ...args: any[]): void {
    console.error(this.formatMessage(LogLevel.ERROR, message, ...args));
  }

  /**
   * 创建子日志记录器
   */
  child(name: string): LoggerService {
    return new LoggerService(`${this.name}:${name}`);
  }
}

export const Logger = new LoggerService('iDoc-mcp');
